package com.neuedu.demoweb.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 登录控制器，控制需要登录才能访问的资源
 * 
 * @author chens
 *
 */
@WebFilter(urlPatterns = { "/pages/*", "/sys/*" })
public class LoginFilter implements Filter {
	private static final String LOGIN_ACTION = "/sys/admin/login";

	public LoginFilter() {

	}

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse rep = (HttpServletResponse) response;
		Object admin = (Object) req.getSession().getAttribute("login_user");

		String uri = req.getRequestURI();
		System.out.println(uri);

		// 如果用户登录成功或执行登录操作或执行注册操作则不拦截
		if (admin != null || uri.indexOf(LOGIN_ACTION) != -1) {
			// session会话中包含还有用户登录系统 ---登录成功；可以访问后面的资源
			chain.doFilter(req, response);
		} else {
			// 使用重定向到登录页面
			rep.sendRedirect(req.getContextPath() + "/login.html");
		}

	}

	@Override
	public void init(FilterConfig fConfig) throws ServletException {

	}

}
